package com.dl.test.controller;

import cn.hutool.core.thread.ThreadUtil;
import com.dl.dlcommon.annotation.MethodInfo;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Scheduler;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author DL
 * @create 2025-03-25 11:13
 */
@MethodInfo(time = true)
@RestController
public class ReactiveController {

    @Resource
    private Scheduler customScheduler;

    @GetMapping("/hello")
    public String hello1() {
        return "Hello, World!";
    }

    @GetMapping("/numbers")
    public List<Integer> numbers1() {
        ThreadUtil.sleep(5000);
        // 返回 1 到 10 的数字流
        return Stream.iterate(1, i -> i + 1).limit(10).collect(Collectors.toList());
    }

    @GetMapping("/r/hello")
    public Mono<String> hello2() {
        return Mono.just("Hello, World!");
    }

    @GetMapping("/r/numbers")
    public Flux<Integer> numbers2() {
        ThreadUtil.sleep(5000);
        // 返回 1 到 10 的数字流
        return Flux.range(1, 10);
    }

    @GetMapping("/blocking")
    public Mono<String> blocking() {
        // 模拟耗时操作（例如数据库查询）
        return Mono.fromCallable(() -> {
            Thread.sleep(2000);
            return "Blocking Response";
        }).subscribeOn(customScheduler);
    }

    @GetMapping("/non-blocking")
    public Mono<String> nonBlocking() throws IOException {
        Flux<String> lines = Flux.fromStream(Files.lines(Paths.get("file.txt")));
        System.out.println("lines = " + lines);
        // 模拟非阻塞操作
        return Mono.delay(Duration.ofSeconds(2))
                .map(delay -> "Non-Blocking Response")
                .subscribeOn(customScheduler);
    }

    @GetMapping("/test")
    public Flux<Long> test() throws IOException {
        // 模拟非阻塞操作
        return Flux.interval(Duration.ofSeconds(1));
    }
}
